package org.example.split;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.example.flink.pojo.WaterSensor;

import java.util.Arrays;

/**
 * @Author: tang
 * @Description:
 * @Date 2025/2/18 10:03
 */
public class FlinkSplit {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment environment = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        environment.setParallelism(4);

        DataStreamSource<String> streamSource = environment.socketTextStream("127.0.0.1", 7777);

        OutputTag<WaterSensor> outputTag1 = new OutputTag<WaterSensor>("s1", Types.POJO(WaterSensor.class));
        OutputTag<WaterSensor> outputTag2 = new OutputTag<WaterSensor>("s2",Types.POJO(WaterSensor.class));

        SingleOutputStreamOperator<WaterSensor> process = streamSource
                .map((MapFunction<String, WaterSensor>) value -> {
                    String[] strings = value.split(",");
                    return new WaterSensor(strings[0], value, Integer.parseInt(strings[1]));
                })
                .process(new ProcessFunction<WaterSensor, WaterSensor>() {
                    @Override
                    public void processElement(WaterSensor waterSensor, ProcessFunction<WaterSensor, WaterSensor>.Context ctx,
                                               Collector<WaterSensor> out) throws Exception {
                        if (waterSensor.getId().startsWith("s1")) {
                            // 输出到分支流
                            ctx.output(outputTag1, waterSensor);
                        } else if (waterSensor.getId().startsWith("s2")) {
                            ctx.output(outputTag2, waterSensor);
                        } else {
                            // 主流
                            out.collect(waterSensor);
                        }

                    }
                }).returns(new TypeHint<WaterSensor>() {});
        // 分支流 s1
        process.getSideOutput(outputTag1).printToErr();
        // 分支流 s2
        process.getSideOutput(outputTag2).printToErr();
        //  主流
        process.print();


        environment.execute();

    }

}
